import { AxiosHttp, HttpError, InterceptorHttp } from './http/index'
import { ResultError, ResultCodes } from './ResultError'
import { getToken } from 'src/utils/auth';

export { ResultError, ResultCodes }


//定义接口的基础返回结构,对于我们现在的项目可能是这样
type BaseResult = {
    data: any,
    code: string,
    success: boolean,
    message: string
}

//创建Http的子类来执行请求
const axiosHttp = new AxiosHttp<BaseResult>({
    // baseURL: 'http://192.168.1.112:8083/',
    // baseURL: 'http://10.18.0.162:8097/',
    baseURL: import.meta.env.VITE_BASE_API as string,
    withCredentials: false,
    timeout: 30000
})


//使用Http的拦截器子类包装一个Http类，以获得对请求的统一处理能力
const http = new InterceptorHttp<BaseResult, any>(axiosHttp, {
    //这里修改请求
    onRequest: (config) => {
        const token = getToken() as string
        if (token && !config.url.startsWith('/auth/login')) {
            config.options.header = config.options.header ?? {}
            config.options.header.RdAuthorization = token
        }
        return config
    },
    //这里修改结果
    onResult: (result) => {
        //对于我们现在的项目，在成功的情况下提取data，失败的情况下转换成Error
        if (result.success) {
            if (result.data?.pageSize !== undefined) {
                result.data.list = result.data.list ?? []
            }
            if (result.data?.size !== undefined && result.data?.pages !== undefined) {
                result.data.list = result.data.records ?? []
                result.data.pageSize = result.data.size
            }
            return result.data
        } else {
            return Promise.reject(new ResultError(result.code, result.message, result.data))
        }
    },
    //这里处理或恢复错误
    onError: (error) => {
        if (error instanceof HttpError) {
            switch (error.response?.status) {
                case 401:
                    getWxCode()
                    break;
                default:
                    break;
            }
        }
        return Promise.reject(error)
    }
})

export default http
